<template>
	<!-- 
	注意
		<up-picker>本项目使用的uview-plus版本为3.4.97,需要更改框架中的inputPropsInner,否者会报警告
	 -->
	<view class="main-box">
		<!-- 注意，
			如果需要兼容微信小程序，最好通过setRules方法设置rules规则
			up-picker-data没有inputProps属性设置输入框样式，需要自己去组件内加
		 -->
		<!-- 表单 -->
		<up-form :model="form"
				 :borderBottom="true"
				 ref="uFormRef"
				 labelWidth="auto"
				 style="padding: 0 20rpx;
						background-color: #ffffff;">
			<up-form-item label="客户"
						  prop="customerSeleted"
						  :borderBottom="true"
						  required>
				<up-input @click="toSelectPage('customerSeleted')"
						  v-model="form.customerSeletedName"
						  placeholder=""
						  border="none"
						  inputAlign="right" />
				<template #right>
					<up-icon name="arrow-right"></up-icon>
				</template>
			</up-form-item>
			<up-form-item label="销售仓库"
						  prop="salesWarehouseSeleted"
						  :borderBottom="true"
						  required>
				<up-picker-data style="width: 100%;"
								:inputProps="{inputAlign:'right',border:'none'}"
								labelKey="whname"
								valueKey="whid"
								v-model="form.salesWarehouseSeleted"
								:options="salesWarehouses"
								:closeOnClickOverlay="true"
								hasInput></up-picker-data>
				<template #right>
					<up-icon name="arrow-right"></up-icon>
				</template>
			</up-form-item>
			<!-- 填写更多 -->
			<view v-show="fillMoreShow">
				<up-form-item label="业务员"
							  prop="salespersonSeleted"
							  :borderBottom="true">
					<up-picker-data style="width: 100%;"
									:inputProps="{
										inputAlign:'right',
										border:'none',
										placeholder:'不填写默认为当前账号'
									}"
									labelKey="nickName"
									valueKey="userId"
									v-model="form.salespersonSeleted"
									:options="salespersons"
									:closeOnClickOverlay="true"
									hasInput></up-picker-data>
					<template #right>
						<up-icon name="arrow-right"></up-icon>
					</template>
				</up-form-item>
			</view>
			<view @click="fillMoreShow = !fillMoreShow"
				  style="display: flex;
						 justify-content: center;
						 padding: 30rpx 0;">
				<up-icon labelPos="left"
						 :label="fillMoreShow?'收起更多':'填写更多'"
						 :name="fillMoreShow?'arrow-up':'arrow-down'"
						 class="right"></up-icon>
			</view>
		</up-form>

		<!-- 加商品 -->
		<drag-button :isDock="true"
					 :existTabBar="true"
					 :initPaddingBottom="200"
					 text="添加"
					 @btnClick="toProductPage"
					 style="padding: 20rpx;" />

		<!-- 商品列表 -->
		<view>
			<!-- 表头 -->
			<view style="font-size: 28rpx;
			             font-weight: 300;
			             background-color: #e3e8fb;
			             padding: 8rpx 20rpx;
			             display: flex;">
				<view style="flex:1">商品</view>
				<view style="width:180rpx">销售价</view>
				<view style="width:180rpx">数量/小计</view>
			</view>
			<!-- 表体 -->
			<view>
				<up-empty v-if="!car || Object.keys(car).length === 0"
						  mode="data"
						  icon="data"></up-empty>
				<view v-else
					  v-for="(item,index) in Object.values(car).flat()"
					  style="background-color: #ffffff;">
					<!-- 一行数据 -->
					<view @click="item.show = !item.show"
						  style="display: flex;
								 padding: 20rpx 20rpx 0 20rpx;">
						<view style="flex:1">
							<view style="font-size: 24rpx;">
								<text style="color: #3c9cff;padding: 4rpx 16rpx;background-color: #edf0f9;">{{index+1}}</text>
								<text style="font-weight: bold;font-size: 30rpx;margin-left: 10rpx;">{{item.pname}}</text>
							</view>
							<view style="font-size: 24rpx;padding: 6rpx 0;">
								<!-- <text>{{formatItemList(item.itemList)}}</text> -->
								<text style="margin-left: 10rpx;">{{item.formulatext}}</text>
							</view>
						</view>
						<view style="width:180rpx;font-weight: bold;font-size: 30rpx;">
							{{'￥'+ item.bigprice + '/' + item.bigunit}}
						</view>
						<view style="width:180rpx">
							<view style="font-weight: bold;font-size: 30rpx;">
								{{formatItemList(item.itemList)}}
							</view>
							<view style="font-size: 24rpx;font-weight: bold;color: #3c9cff;">
								{{'￥' + formatCountPrice(item.itemList)}}

							</view>
						</view>
					</view>

					<!-- 点击后可以编辑数量 -->
					<view v-show="item.show"
						  style="padding: 0 20rpx;">
						<view v-if="item.bigunit"
							  v-for="(u_item,u_index) in item.itemList"
							  style="display: flex;
							  			 margin-top: 20rpx;">
							<button v-if="u_item.saletype!='常规销售'"
									@click="showPopup(item)"
									size="mini"
									style="display: flex;
										   align-items: center; 
										   border:2rpx solid #000;
										   border-radius: 50rpx;
										   padding: 0 20rpx;
										   margin-left: 0;
										   background-color: #f3f2f7;">
								<text style="padding: 0 20rpx;
											 border-radius: 50%;
											 background-color:#e36a4e ;
											 color:#fff">
									{{u_item.saletype.slice(-1)}}
								</text>
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
								<up-icon name="arrow-down-fill"
										 style="margin-left: 10rpx;"></up-icon>
							</button>
							<button v-else
									size="mini"
									style="display: flex;align-items: center; border:2rpx solid #000;border-radius: 50rpx;padding: 0 20rpx;margin-left: 0;background-color: #f3f2f7;">
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
							</button>
							<up-number-box v-model="u_item.number"
										   buttonSize="25"
										   buttonWidth="25"
										   min="0"
										   @change="countChange($event,item.brand,item.pid)"
										   integer></up-number-box>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 0元赠弹出层 -->
		<popupGive :show="popupShow"
				   :productData="currentConfigProduct"
				   @close="popupClose"
				   @confirm="handleConfigConfirm"></popupGive>

		<!-- 占位置 -->
		<view :style="{height:paddingBottom+'px'}"></view>
		<view id="bottom-box"
			  style="background-color: #ffffff;
					 position: fixed;
					 bottom: 0;
					 left: 0;
					 width: 100%;
					 z-index: 998;
					 box-sizing: content-box;
					 border-top: 1px solid #dedede;
					 padding-bottom: env(safe-area-inset-bottom);">
			<view style="display: flex;
						 padding: 20rpx 20rpx 0 20rpx;">
				<view style="margin-left: auto;">
					<text>合计：</text>
					<text style="font-size: 48rpx;
								 color:#C06E5D;
								 font-weight: bold;">￥{{getCartTotal}}</text>
				</view>
			</view>
			<view style="padding: 20rpx;">
				<up-button type="primary"
						   @click="submitForm">提交</up-button>
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		watch,
		nextTick,
		computed
	} from 'vue'
	import {
		onReady,
		onLoad
	} from "@dcloudio/uni-app"
	import {
		useStore
	} from "vuex";
	import {
		timeFrom
	} from '@/uni_modules/uview-plus';
	const store = useStore();
	const app = getApp()

	onReady(async () => {
		// 如果需要兼容微信小程序，最好通过setRules方法设置rules规则
		uFormRef.value.setRules(rules.value)
		//.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
		uni.createSelectorQuery().select('#bottom-box').boundingClientRect(
			b_data => {
				paddingBottom.value = b_data.height
			}).exec()
	})
	onLoad(async () => {
		const res = await app.globalData.http.get("/wms/warehouse/list")
		salesWarehouses.value = res.rows
		const user = await app.globalData.http.get("/wms/common/list/user")
		salespersons.value = user.userList
	})

	// 布局_底部
	const paddingBottom = ref(0)
	// data_车销订单表单数据
	const form = ref({
		// 客户
		customerSeleted: null,
		customerSeletedName: "",
		// 销售仓库
		salesWarehouseSeleted: null,
		// 业务员
		salespersonSeleted: null, // 不填写默认为当前登录人
		// 整单优惠
		discount: 0
	})
	// data_购物车
	const car = ref({})
	// data_当前要配置的产品数据
	const currentConfigProduct = ref({})
	// picker_销售仓库
	const salesWarehouses = ref([])
	// picker_销售员
	const salespersons = ref([])
	// 开关_填写更多
	const fillMoreShow = ref(false);
	// 开关_popup
	const popupShow = ref(false)
	// 表单引用
	const uFormRef = ref(null);

	const setCar = (e) => {
		car.value = e
	}
	
	// 格式化小计 如“3箱1瓶”  在Vue中，计算属性（computed）‌默认不能直接接收外部参数‌，
	const formatItemList = (itemList) => {
		if (!itemList?.length) return ''
		// 按单位分组求和
		const grouped = itemList.reduce((acc, item) => {
			const unit = item.unit || ''
			const number = parseInt(item.number) || 0
			acc[unit] = (acc[unit] || 0) + number
			return acc
		}, {})
		// 格式化输出：19箱10瓶
		return Object.entries(grouped)
			.filter(([unit, total]) => total > 0)
			.map(([unit, total]) => `${total}${unit}`)
			.join('')
	}
	
	// 小计
	const formatCountPrice = (itemList) => {
		return itemList.reduce((total, item) => {
			return total + (item.unitprice * item.number);
		}, 0);
	};
	
	// 购物车合计
	const getCartTotal = computed(() => {
		let total = 0;
		// 遍历所有品牌
		Object.values(car.value).forEach(brandProducts => {
			// 遍历该品牌下的所有商品
			brandProducts.forEach(product => {
				// 计算该商品的小计
				const productTotal = product.itemList.reduce((sum, item) => {
					return sum + (item.unitprice * item.number);
				}, 0);
				total += productTotal;
			});
		});
		// 减去整单优惠
		return total - form.value.discount;
	})
	
	// 检查购物车是否为空
	const isCartEmpty = (car) => {
		// 检查 car 是否为空对象或不存在
		if (!car || Object.keys(car).length === 0) {
			return true;
		}
		// 检查所有品牌下是否都没有商品
		return Object.values(car).every(brandProducts =>
			!brandProducts || brandProducts.length === 0
		);
	};
	
	
	// 修改 showPopup 方法，直接接收并设置产品数据
	const showPopup = async (productData) => {
		currentConfigProduct.value = productData
		await nextTick();
		// 确保索引和产品数据同步
		popupShow.value = true
	}
	const popupClose = () => {
		popupShow.value = false
	}
	// 处理配置确认 - 替换原来的 sureGive 方法
	const handleConfigConfirm = async (configData) => {
		const {
			businessType,
			unit,
			unitPrice
		} = configData
		await nextTick();
		// 更新当前产品的itemList配置
		currentConfigProduct.value.itemList.forEach((item, index) => {
			if (item.saletype != '常规销售') {
				item.unit = unit
				item.saletype = businessType
				item.unitprice = unitPrice
			}
		})
		// 修改car中的数据
		const brandId = currentConfigProduct.value.brand
		// 确保该品牌的数组存在
		if (car.value[brandId]) {
			const productIndex = car.value[brandId].findIndex(cartItem =>
				cartItem.pid === currentConfigProduct.value.pid
			)
			if (productIndex !== -1) {
				// 如果购物车中已存在此商品，更新它
				car.value[brandId][productIndex] = currentConfigProduct.value
			}
			console.log(car.value)
		}
	}
	// itemList数量变化 brandId为中文字符串如"一担粮",其实每一个商品中有一个brand字段
	const countChange = async (e, brandId, pid) => {
		await nextTick();
		if (car.value[brandId]) { // 如果所有number都为0，说明此前不是都为0，那么car中一定会有brandId
			const productIndex = car.value[brandId].findIndex(cartItem => {
				return cartItem.pid === pid
			});
			if (productIndex !== -1) { // 说明找到了
				// 检查当前商品的所有itemList的number是否都为0
				const allItemsZero = car.value[brandId][productIndex].itemList.every(
					item => {
						return item.number === 0
					});
				if (allItemsZero) {
					// const flag = await app.globalData.modal.confirm("是否去掉此商品")
					car.value[brandId].splice(productIndex, 1);
					// 如果该品牌下没有商品了，删除整个品牌
					if (car.value[brandId].length === 0) {
						delete car.value[brandId];
					}
				}
			}
		}
		console.log(car.value)
	}
	// 去选择客户 仓库页
	const toSelectPage = async (type) => {
		if (type === "customerSeleted") {
			uni.navigateTo({
				url: '/pages/selectCus'
			})
		} else if (type === "salesWarehouseSeleted") {}
	}
	// 选择客户
	const setCus = (id, name) => {
		form.value.customerSeleted = id
		form.value.customerSeletedName = name
	}
	const toProductPage = () => {
		// url有长度限制，太长的字符串会传递失败，可改用窗体通信
		uni.navigateTo({
			url: `/pages/addProduct`,
			success: (res) => { // 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('setCar', car.value)
			}
		})
	}
	const rules = ref({
		customerSeleted: [{
			required: true,
			type: 'number',
			message: '请选择客户',
			trigger: ['change', 'blur'],
		}],
		salesWarehouseSeleted: [{
			required: true,
			type: 'number',
			message: '请选择仓库',
			trigger: ['change', 'blur'],
		}]
	})
	// 监听 form.number 的变化解决picker第一次选择后不触发form的表单校验的bug
	watch(() => form.value.customerSeleted, (newVal, oldVal) => {
		console.log(`Number changed from ${oldVal} to ${newVal}`);
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('customerSeleted');
			}
		}
	});
	watch(() => form.value.salesWarehouseSeleted, (newVal, oldVal) => {
		console.log(`Number changed from ${oldVal} to ${newVal}`);
		if (oldVal == null) { // 只执行一次
			if (uFormRef.value) {
				uFormRef.value.validateField('salesWarehouseSeleted');
			}
		}
	});
	// 提交方法
	const submitForm = () => {
		uFormRef.value.validate().then(async (valid) => {
			if (valid) {
				// 判断car是不是空的，不是空的才请求提交订单
				const isEmpty = isCartEmpty(car.value)
				if (isEmpty) {
					uni.$u.toast('你还未添加任何商品')
					return
				}
				// 不要number为0的
				const insertRecords = Object.values(car.value)
					.flat()
					.flatMap(product =>
						product.itemList
						.filter(item => item.number > 0)
						.map(item => ({
							...item,
							pname: product.pname // 这里会覆盖item原有的pname
						}))
					)
				const obj = {
					cusid: form.value.customerSeleted,
					whid: form.value.salesWarehouseSeleted,
					owner: form.value.salespersonSeleted ? form.value
						.salespersonSeleted : store.state.user.userId,
					type: "车销订单",
					shtime: timeFrom(new Date)
				}
				const param = {
					action: 'add',
					obj: obj,
					insertRecords: insertRecords,
					removeRecords: [],
					updateRecords: [],
				}
				const res = await app.globalData.http.put("/wms/sale", param)
				uni.redirectTo({
					url: `/pages/carSaleOrderDetail?saleId=${res.saleid}`
				})
			} else {
				console.log(valid)
			}
		}).catch(() => {
			// 处理验证错误  
		});
	}
	// 一定要放在最后，不然会报错
	defineExpose({
		setCus,
		setCar
	})
</script>

<style lang="scss"
	   scoped>
	
</style>